from PIL import Image
import base64
from io import BytesIO

def read_image(input_path):
    # 打开图片
    image = Image.open(input_path)

    # 将图片保存到内存中
    byte_stream = BytesIO()
    image.save(byte_stream, format='PNG')
    byte_stream.seek(0)

    # 将图片转换为 Base64 编码的字符串
    encoded_image = base64.b64encode(byte_stream.read()).decode('utf-8')

    # 创建 Data URL，即 Blob 链接
    blob_url = f'data:image/png;base64,{encoded_image}'

    return blob_url

def resize_image_with_max_dimensions(input_path, max_width, max_height):
    # 打开图片
    image = Image.open(input_path)

    # 获取原始图片的宽度和高度
    original_width, original_height = image.size

    # 计算缩放比例
    width_ratio = max_width / original_width
    height_ratio = max_height / original_height

    # 使用最小的比例进行缩放，以保持原始比例
    resize_ratio = min(width_ratio, height_ratio)

    # 计算缩放后的尺寸
    new_width = int(original_width * resize_ratio)
    new_height = int(original_height * resize_ratio)

    # 缩放图片
    resized_image = image.resize((new_width, new_height), Image.DEFAULT_STRATEGY)
    
    # 将图片保存到内存中
    byte_stream = BytesIO()
    resized_image.save(byte_stream, format='PNG')
    byte_stream.seek(0)

    # 将图片转换为 Base64 编码的字符串
    encoded_image = base64.b64encode(byte_stream.read()).decode('utf-8')

    # 创建 Data URL，即 Blob 链接
    blob_url = f'data:image/png;base64,{encoded_image}'

    return blob_url

  
if __name__ == '__main__':
    input_path = 'input_image.jpg'
    output_path = 'output_image.jpg'
    max_width = 300
    max_height = 200

    resize_image_with_max_dimensions(input_path, output_path, max_width, max_height)

